package com.lhy.skywalking.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhy.skywalking.product.dto.ProductDTO;
import com.lhy.skywalking.product.entity.Product;
import com.lhy.skywalking.product.mapper.ProductMapper;
import com.lhy.skywalking.product.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ProductDTO getProductById(Serializable id) {
        String key = "sk:products:" + id;
        Object json = redisTemplate.opsForValue().get(key);
        Product product = null;
        if (json != null) {
            product = (Product) json;
        } else {
            product = getBaseMapper().selectById(id);
            if (product != null) {
                redisTemplate.opsForValue().set(key, product, 2, TimeUnit.HOURS);
            } else {
                return null;
            }
        }
        ProductDTO productDTO = new ProductDTO();
        BeanUtils.copyProperties(product, productDTO);
        return productDTO;
    }

}
